﻿# -*- coding:utf-8 -*-
#
# склад
#
import datetime
from django.shortcuts import render_to_response
from django.shortcuts import get_object_or_404
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from django.template import RequestContext, Context
from django.core.urlresolvers import reverse
from django.db.models import Sum, Count



from sklad.forms import CategoryForm, PartForm #DocumentForm,  DocumentReceiptForm, DocumentDeliveryForm Max, , StdDev, VarianceMin, Avg, 
from sklad.models import Category, Part, Document, DocumentReceipt, DocumentDelivery, Unit, Waybill


from sklad.contextprocessors import category_proc



def category_process(request, catid, template_file):
    category = get_object_or_404(Category, id=catid)
    #if request.session["current_category"] == None:
    #    request.session["current_category"] = catid
    #if int(catid) in request.session["expanded_catid"]:
    #    request.session["expanded_catid"].remove(int(catid))
        
    partlist = Part.objects.select_related().filter(category=request.session["current_category"])
    qs = Waybill.objects.filter(part__category=category)
    qs.query.group_by = ['part_id']
    partlist = qs.annotate(Sum("count")).order_by("part")  
    
    sub_categories = Category.objects.filter(parent=request.session["current_category"])
    context = Context({
      'category':category,
      'partlist': partlist,
      'sub_categories':sub_categories,
    })
    return render_to_response(template_file, context,  context_instance=RequestContext(request, processors=[category_proc]))





#@login_required
def view(request, catid):
    request.session["current_category"] = int(catid)    
    return category_process(request, catid, 'sklad/category_part.html')



#@login_required
def collaps(request, catid):
    if int(catid) in request.session["expanded_catid"]:
        request.session["expanded_catid"].remove(int(catid))
    return category_process(request, catid, 'sklad/category_part.html')




#@login_required
def expand(request, catid):
    if int(catid) not in request.session["expanded_catid"]:
        request.session["expanded_catid"].append(int(catid))  
    return category_process(request, catid, 'sklad/category_part.html')




#@login_required
def edit(request, catid):
    cat_inst = Category.objects.get(id=catid)
    if request.method == 'POST':
        form = CategoryForm(request.POST,  instance=cat_inst)
        if form.is_valid():
            category = form.save(commit=False)
            category.user = request.user
            category.save()
            return HttpResponseRedirect( reverse('category_view', args=[(request.session["current_category"])]) )
    else:
        form = CategoryForm(instance=cat_inst)
    return render_to_response('sklad/form_category_edit.html', locals(), context_instance=RequestContext(request, processors=[category_proc]))





@login_required
def create(request, catid):
    if request.method == 'POST':
        form = CategoryForm(request.POST)
        if form.is_valid():
            category = form.save(commit=False)
            category.user = request.user
            request.session["current_category"] = category.id
            category.save()
            return HttpResponseRedirect(reverse('category_view', args=[category.id]))
    else:
        form = CategoryForm(initial={'parent': catid})
    return render_to_response('sklad/form_category_add.html', locals(), context_instance=RequestContext(request, processors=[category_proc]))


@login_required
def create_root(request):
    if request.method == 'POST':
        form = CategoryForm(request.user.id, request.POST)
        if form.is_valid():
            category = form.save(commit=False)
            category.user = request.user
            request.session["current_category"] = category.id
            category.save()
            return HttpResponseRedirect(reverse('category_view', args=[category.id]))
    else:
        form = CategoryForm(request.user, initial={'parent': None})
    return render_to_response('sklad/form_category_add_root.html', locals(), context_instance=RequestContext(request, processors=[category_proc]))





@login_required
def delete(request, item):
    pass
    
   




